package com.rxb.blog.controller;

import com.rxb.blog.common.CommonResult;
import com.rxb.blog.service.FileService;
import com.rxb.blog.utils.FileUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Author：rxb
 * Date：2020-02-28 14:45
 * Description：<描述>
 */
@Api(description = "文件相关接口")
@RestController
@RequestMapping("file")
public class FileController {

    @Autowired
    private FileService fileService;

    @Value("${blog.picUrl}")
    private String picUrl;

    @ApiOperation(value = "上传文件", notes="上传文件")
    @ApiImplicitParam(name = "file", value = "文件接收", paramType = "query", required = true, dataType = "MultipartFile")
    @PostMapping("uploadFile")
    public CommonResult<String> uploadFile(@RequestParam("file") MultipartFile file){
        String uuid = fileService.uploadFile(file);
        return CommonResult.success(uuid);
    }

    @ApiOperation(value = "批量上传文件", notes="批量上传文件")
    @ApiImplicitParam(name = "file", value = "文件接收", paramType = "query", required = true, dataType = "MultipartFile")
    @PostMapping("uploadFilePi")
    public CommonResult<List<String>> uploadFilePi(@RequestParam("file") MultipartFile[] files){
        List<String> list = new ArrayList<>();
        if(null != files && files.length > 0){
            //遍历并保存文件
            for(MultipartFile file : files){
                String uuid = fileService.uploadFile(file);
                String originalFilename = file.getOriginalFilename();
                String targetPathSuffix = originalFilename.substring(originalFilename.lastIndexOf("."));

                list.add(picUrl+ File.separator+uuid+targetPathSuffix);
            }
        }

        return CommonResult.success(list);
    }

    @ApiOperation(value = "删除文件", notes="删除文件")
    @ApiImplicitParam(name = "filePath", value = "文件路径", paramType = "query", required = true, dataType = "String")
    @PostMapping("deleteFile")
    public CommonResult<String> deleteFile(@RequestBody Map map){
        FileUtil.deleteFile(map.get("filePath").toString());
        // 将关联的 博客类型表  中的
        fileService.delete((Integer)map.get("picture_id"));

        return CommonResult.success("删除文件成功");
    }
}
